import Taro from '@tarojs/taro';
import {Image, View, Text, Swiper, SwiperItem, Button, Textarea, RichText} from '@tarojs/components';
import {AtInput} from 'taro-ui';
import {connect} from "@tarojs/redux";
import {actionCreator} from "../../../store/actions";
import {appConfig, request, unite} from '../../../utils/index';
import head from "../../../asset/shop/shop.png";
import UnionidModal from "../../../components/unionid-modal/unionidModal";
import PhoneModal from "../../../components/phone-modal/phoneModal";
import Ai from "../../../asset/images/ai.png";
import AiIn from "../../../asset/images/ai_in.png";
import Gd from "../../../asset/images/gd_icon.png";
import Zan from "../../../asset/images/zan.png";
import ZanIn from "../../../asset/images/zan_in.png";
import addressIcon from "../../../asset/images/address_icon.png";
import Can from "../../../asset/images/can.png";
import './detail.scss';

class Detail extends Taro.Component {
    config = {
        navigationBarTitleText: '',
        backgroundColor: '#fff',
    };

    state = {
        search: '', //输入内容
        contentData: [], //详情
        contentDataTitle: '',
        commentList: [1,1,1,1,1,1], //评论列表
        unionId: false,
        phoneId: false,
        heights: 0,
        moreStatus: false, //更多弹窗
    };

    temp = {
        isLoading: false,
    };

    componentDidMount() {
        this.init();
    }

    init = () => {
        const option = this.$router.params;
        const params = {
            url: '/momments/detail',
            data:{
                dispatchId: option.id,
                mommentId: option.dtId,
            }
        };
        request(params, false).then(res => {
            if (res && res.data) {
                let content = res.data.content;
                let text =  content.replace(/↵/g, '\n'); ////正则全局替换
                this.setState({
                    contentData: res.data,
                    contentDataTitle: text,
                    commentList: res.data.comments, //评论列表
                }, () => {
                    console.log(JSON.stringify(this.state.contentDataTitle) + 'contentDataTitle')
                    let query = wx.createSelectorQuery();
                    setTimeout(() => {
                        var heig = 0;
                        query.selectAll('.head-imgs').boundingClientRect(rect=>{
                            // heig = rect.height;
                            console.log(rect);
                            rect.forEach((item) => {
                                console.log(item.height);
                                console.log(Number(item.height) > Number(heig));
                               if (Number(item.height) > Number(heig)) {
                                   heig = item.height;
                               }
                            });
                            this.setState({
                                heights: heig
                            }, () => {
                                console.log(this.state.heights)
                            })
                        }).exec();

                    },500);
                });
                Taro.setNavigationBarTitle({
                    title: res.data.title
                })
            }
        });
    };

    //input内容保存
    datum = (name,val) => {
        this.setState({
            [name]: val
        })
    };

    datumText = (name, val) => {
        // console.log(JSON.stringify(val) + 'E')
        this.setState({
            [name]: val.detail.value
        })
    };

    //提交
    sumbit = () => {
        const {search} = this.state;
        const {mobileFlag, existUser} = this.props;
        const option = this.$router.params;
        if (existUser == 0) { //未授权用户信息
            this.setState({
                unionId: true
            });
            return;
        }
        if (mobileFlag == 0) { //未授权手机号
            this.setState({
                phoneId: true
            });
            return;
        }
        if (!search) return unite.showToast('请输入评论内容');
        if(this.temp.isLoading) return;
        this.temp.isLoading = true;
        const params = {
            url: '/momments/replyTo',
            data:{
                mommentId:  option.dtId,
                content: search,
            }
        };
        request(params).then(res => {
            this.temp.isLoading = false; //防止多次
            if (res) {
                if(res.code == 200) {
                    unite.showToast('评论成功');
                    this.setState({
                        search: ''
                    }, () => {
                        this.init();
                    });
                }
            }
        })
    };

    unGetUserInfo = (is) => {
        const {mobileFlag, setExistUser} = this.props;
        if (is) {
            setExistUser(1);
            this.setState({
                phoneId: mobileFlag == 0 ? true : false
            })
        }
        this.setState({
            unionId: false, //关闭 nu ni id 弹窗
        });
    };

    //授权手机号
    unGetPhone = (is) => {
        const {setMobileFlag} = this.props;
        if (is) {
            setMobileFlag(1);
        }
        this.setState({
            phoneId: false, //关闭弹窗
        });
    };

    //跳转课程详情
    skipCourseDetail = (classId, dispatchId, reservedStatus) => {
        Taro.navigateTo({
            url: '../../index/course-detail/courseDetail?classId=' + classId + '&dispatchId=' + dispatchId + '&reservedStatus=' + reservedStatus,
        })
    };

    //评论区点赞 取消赞
    isZan = (is, id) => {
    //    0未点赞，1已点赞
        if(this.temp.isLoading) return;
        this.temp.isLoading = true;
        const needLoading = false;
        const params = {
            url: '/momments/likeOpt',
            data:{
                opt:  is == 0 ? 1 : 0,
                type: 1,
                uid: id,
            }
        };
        request(params, needLoading).then(res => {
            this.temp.isLoading = false; //防止多次
            if (res) {
                if(res.code == 200) {
                    this.init();
                }
            }
        })
    };

    //动态点赞 取消赞
    isShouc = (is) => {
        const option = this.$router.params;
        //    0未点赞，1已点赞
        if(this.temp.isLoading) return;
        this.temp.isLoading = true;
        const params = {
            url: '/momments/likeOpt',
            data:{
                opt:  is == 0 ? 1 : 0,
                type: 0,
                uid: option.dtId,
            }
        };
        request(params, '', '', '', false).then(res => {
            this.temp.isLoading = false; //防止多次
            if (res) {
                if(res.code == 200) {
                    this.init();
                }
            }
        })
    };

    //分享
    onShareAppMessage () {
        const option = this.$router.params;
        return {
            title: '动态镜子',
            path:  `pages/home/detail/detail?id=${option.id}&dtId=${option.dtId}`
        }
    }

    //跳转教练详情
    skipTrainDetail = (id, e) => {
        e.stopPropagation(); //防止父级点击事件干扰
        Taro.navigateTo({
            url: '../../index/train-detail/trainDetail?id=' + id
        })
    };

    //更多弹窗
    setGetMore = () => {
      this.setState(prevState => ({
          moreStatus: !prevState.moreStatus
      }));
    };

    //删除动态
    deleteDt = () => {
        const option = this.$router.params;
        const {getbackPage} = this.props;
        if(this.temp.isLoading) return;
        this.temp.isLoading = true;
        const params = {
            url: '/momments/delete?momentId=' + option.dtId,
            data:{
                momentId: Number(option.dtId),
            }
        };
        request(params, '', '', '', false).then(res => {
            this.temp.isLoading = false; //防止多次
            if (res) {
                if(res.code == 200) {
                    unite.showToast('删除成功');
                    getbackPage('1');
                    setTimeout(() => {
                        Taro.navigateBack({delta: 1})
                    }, 1500)
                }
            }
        })
    };

    //跳转教室地图导航
    goToMap = () => {
        const {contentData} = this.state;
        if (contentData.latitude) {
            Taro.openLocation({
                latitude: Number(contentData.latitude),
                longitude: Number(contentData.longitude),
                address: contentData.address
            })
        } else {
            unite.showToast('该动态信息暂无位置');
        }
    };

    render() {
        const {commentList, search, contentData, unionId, phoneId, heights, moreStatus, contentDataTitle} = this.state;
        return (
            <View className="page">
                <View className="head-img-wrap">
                    <Image className="head-ai" onClick={this.isShouc.bind(this, contentData.isLike)} src={contentData.isLike == 1 ? AiIn : Ai} mode="aspectFit"/>
                    {/*<Button className="head-fb"  open-type="share">*/}
                    {/*    <Image className="head-fb-img" src={Gd} onClick={this.onShareAppMessage} mode="aspectFit"/>*/}
                    {/*</Button>*/}
                    <View className="head-fb">
                        <Image className="head-fb-img" src={Gd} onClick={this.setGetMore} mode="aspectFit"/>
                    </View>
                    <View>
                        <Swiper
                            className='test-h'
                            indicatorColor='rgba(0, 0, 0, 0.2)'
                            indicatorActiveColor='#FFFFFF'
                            circular
                            style={'height: 0px; overflow: hidden;'}
                            indicatorDots
                        >
                            {contentData.imgs.map((item, index) => (
                                <SwiperItem key={index}>
                                    <Image
                                        className="head-imgs"
                                        mode="widthFix"
                                        src={item.imgUrl}
                                    />
                                </SwiperItem>
                            ))}
                        </Swiper>
                    </View>
                    {heights && (
                        <Swiper
                            className='test-h'
                            style={'height:' + heights + 'px;'}
                            indicatorColor='rgba(0, 0, 0, 0.2)'
                            indicatorActiveColor='#FFFFFF'
                            circularhasDelete
                            indicatorDots
                        >
                            {contentData.imgs.map((item, index) => (
                                <SwiperItem key={index} className="flex-center">
                                    <Image
                                        className="head-imgs"
                                        mode="widthFix"
                                        src={item.imgUrl}
                                    />
                                </SwiperItem>
                            ))}
                        </Swiper>
                    )}
                </View>
                <View className="head-title-wrap">
                    <View className="text text-overflow">{contentData.title}</View>
                    <Text className="title">{contentDataTitle}</Text>
                    <View className="flex-lr timer">
                        {(contentData.address && contentData.latitude) ? (
                            <View className="flex-l" onClick={this.goToMap}>
                                <Image className="address-img" src={addressIcon} mode="aspectFit"/>
                                <View className="address">{contentData.address}</View>
                            </View>
                        ) : (
                            <View></View>
                        )}
                        <View>{contentData.publishDate}</View>
                    </View>
                    {contentData.weiXinClassDetailResp && (
                        <View className="shop-wrap">
                            <View className="shop-list flex-top" onClick={this.skipCourseDetail.bind(this, contentData.weiXinClassDetailResp.classId, contentData.weiXinClassDetailResp.dispatchId, contentData.weiXinClassDetailResp.reservedStatus)}>
                                <View className="flex-top-l">
                                    <View className="heads" onClick={this.skipTrainDetail.bind(this, contentData.weiXinClassDetailResp.coachInfo.coachId)}>
                                        <Image className="mgs" src={contentData.weiXinClassDetailResp.coachInfo.avatar}/>
                                    </View>
                                    <View>
                                        <View className="name">{contentData.weiXinClassDetailResp.className}</View>
                                        <View className="time">{contentData.weiXinClassDetailResp.classDate +' ' + contentData.weiXinClassDetailResp.classWeekDay + ' ' +contentData.weiXinClassDetailResp.classBeginTime + '-' +contentData.weiXinClassDetailResp.classEndTime}</View>
                                        <View className="biaoti flex-l">
                                            {contentData.weiXinClassDetailResp.labelNames.map((items, indexs) => (
                                                <View className="kepp-gg" key={indexs}>{items}</View>
                                            ))}
                                        </View>
                                    </View>
                                </View>
                                <View className="flex-center btns-skip">查看</View>
                            </View>
                        </View>
                    )}
                </View>
                <View className="comment-wrap">
                    <View className="comment-text">共{commentList.length}条评论</View>
                    {commentList && commentList.map((item, index) => (
                        <View className="comment-list flex-top" key={index}>
                            <View className="head-img-wrap">
                                <Image className="imgs" src={item.userAvatar}/>
                            </View>
                            <View className="comment-titles">
                                <View className="name">{item.userName}</View>
                                <View className="flex-lr timer">
                                    <View>{item.replyDate}</View>
                                    <View className="flex-r zan-text" onClick={this.isZan.bind(this, item.isLike, item.commentId)}>
                                        <View>{item.likeCount}</View>
                                        <Image className="head-zan" src={item.isLike == 1 ? ZanIn : Zan} mode="aspectFit"/>
                                    </View>
                                </View>
                                <View className="title">{item.content}</View>
                            </View>
                        </View>
                    ))}
                </View>
                <View className="report-comment flex-lr">
                    <View className="inp-wrap flex-l">
                        <Textarea
                            className="ins"
                            placeholder='说点什么…'
                            onChange={this.datumText.bind(this, 'search')}
                            onBlur={this.datumText.bind(this, 'search')}
                            onInput={this.datumText.bind(this, 'search')}
                            auto-height
                            value={search}
                            maxlength={-1}
                        />
                        {/*<AtInput*/}
                        {/*    border={false}*/}
                        {/*    className="ins"*/}
                        {/*    name='realName'*/}
                        {/*    type='text'*/}
                        {/*    placeholder='说点什么…'*/}
                        {/*    value={search}*/}
                        {/*    onChange={this.datum.bind(this, 'search')}*/}
                        {/*    onBlur={this.datum.bind(this, 'search')}*/}
                        {/*    onConfirm={this.sumbit}*/}
                        {/*/>*/}
                    </View>
                    <View className="comment-btn flex-center" onClick={this.sumbit}>发布</View>
                </View>
                {unionId &&(
                    <UnionidModal onCancel={this.unGetUserInfo}/>
                )}
                {phoneId &&(
                    <PhoneModal onCancel={this.unGetPhone}/>
                )}
                {moreStatus && (
                    <View className="model-type flex-bottom" onClick={this.setGetMore}>
                        <View className="more-content-wrap">
                            <Button className="list-text flex-center"  open-type="share" onClick={this.onShareAppMessage}>分享给朋友</Button>
                            {contentData.hasDelete == 'Y' &&(
                                <View className="list-text list-text-delete flex-center" onClick={this.deleteDt}>删除动态</View>
                            )}
                            <View className="cancel-text flex-center">取消</View>
                        </View>
                    </View>
                )}
            </View>
        )
    }
}

const mapStateToProps = state => {
    let {mobileFlag, existUser} = state;
    return {
        mobileFlag,
        existUser
    }
};

const mapDispatchToProps = {
    setExistUser: actionCreator.setExistUser,
    setMobileFlag: actionCreator.setMobileFlag,
    getbackPage: actionCreator.getbackPage
};

export default connect(mapStateToProps, mapDispatchToProps)(Detail);



